# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict
import requests

from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import SignError, NotPayOrderError, ProcessedPayOrderError, NotResponsePayIdError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10071': {
        'API_KEY': 'f9832fa86d465039c88b934d093dbd9e',
    },
    # 更换网关地址
    'gateway': 'https://tike.njktfc.com/api/shark/topay',
    'query_gateway': 'https://tike.njktfc.com/api/shark/order/queryOrder',
    # 'gateway': 'https://proud.yiface.net/api/shark/topay',
    # 'query_gateway': 'https://proud.yiface.net/api/shark/order/queryOrder',
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _get_query_gateway():
    return APP_CONF['query_gateway']


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    return m.hexdigest()


#  创建订单sign
def generate_verify_sign(parameter, key):
    s = '%s%s%s%s%s%s' % (parameter['mercId'], parameter['money'], parameter['notifyUrl'],
                          parameter['tradeNo'], parameter['type'], key)
    return _gen_sign(s)


# 创建订单返回数据的签名验证
def generate_response_sign(parameter, key):
    s = '%s%s%s' % (parameter['oid'], parameter['payUrl'], key)
    sign = parameter['sign']
    if sign != _gen_sign(s):
        _LOGGER.info("shayupay sign: %s, calculated sign: %s", sign, _gen_sign(s))
        raise SignError('sign not pass, data: %s' % parameter)


# 异步回调签名验证
def verify_notify_sign(parameter, key):
    s = '%s%s%s%s%s%s' % (parameter['code'], parameter['mercId'], parameter['oid'],
                          parameter['payMoney'], parameter['tradeNo'], key)
    sign = parameter['sign']
    calculated_sign = _gen_sign(s)
    if sign != calculated_sign:
        _LOGGER.info("shayupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise SignError('sign not pass, data: %s' % parameter)


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)

    parm_info = OrderedDict((
        ('playerId', str(pay.id)),
        ('playerIp', _get_device_ip(info)),
        ('deviceId', str(pay.id)),
        ('deviceType', 'android'),
    ))
    parameter_dict = OrderedDict((
        ('mercId', app_id),  # 商户ID
        ('tradeNo', str(pay.id)),  # 商户订单号
        ('type', service),
        ('money', '%.2f' % float(pay_amount)),  # 支付金额 元
        ('notifyUrl', '{}/pay/api/{}/shayupay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('info', parm_info),
        ('time', str(int(round(time.time() * 1000)))),  # 时间戳13位
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)

    json_parameter = json.dumps(parameter_dict)
    _LOGGER.info("shayupay create date: %s, order_id is: %s", json_parameter,
                 parameter_dict['tradeNo'])
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_gateway(), data=json_parameter, headers=headers, timeout=5)
    if response.status_code != 200:
        _LOGGER.info('shayupay response err status_code: %s', response.status_code)
        return {'charge_info': response.status_code}
    _LOGGER.info("shayupay response: %s", response.text)
    resp_obj = json.loads(response.text)

    if resp_obj['code'] == 200:
        data = resp_obj['msg']
        generate_response_sign(data, api_key)
        url = data['payUrl']
        _LOGGER.info('shayupay to pay url: %s', url)
        return {'charge_info': url}
    _LOGGER.info('shayupay to pay err: %s', resp_obj['err'])
    return {'charge_info': resp_obj['err']}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("shayupay notify body: %s", request.body)
    data = json.loads(request.body)
    _LOGGER.info("shayupay notify data: %s, order_id is: %s", data, data['tradeNo'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['tradeNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("shayupay notify fatal error, pay object not exists, data: %s" % data)
        raise NotResponsePayIdError('event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise NotPayOrderError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ProcessedPayOrderError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = ''
    trade_no = data['tradeNo']
    total_fee = float(data['payMoney'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付成功才回调
    _LOGGER.info('shayupay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
    add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    pay = get_pay(pay_id)
    parameter_dict = OrderedDict((
        ('mercId', app_id),  # 商户ID
        ('tradeNo', str(pay.id)),  # 商户订单号
    ))
    _LOGGER.info('shayupay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['tradeNo'])
    response = requests.get(_get_query_gateway(), data=parameter_dict, timeout=5)
    data = json.loads(response.text)
    _LOGGER.info('shayupay query rsp, %s', data)

    if data['code'] == 200:
        data = data['msg']
        trade_status = str(data['payStatus'])
        total_fee = float(data.get('payMoney'))
        trade_no = str(data['tradeNo'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        check_channel_order(pay_id, total_fee, app_id)
        #
        if trade_status == '已支付':
            _LOGGER.info('shayupay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info(
                'shayupay query order success,but not pay success or has been processed, status:%s' % trade_status)
    else:
        _LOGGER.warn('shayupay query data error, error message: %s', data['err'])
